using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;

namespace GEContentPipeline
{
    public class GEAnimationPlayer
    {
        GEAnimationClip currentAnimation;
        TimeSpan currentTime;
        int currentKeyframe;

        Matrix keyframe;

        GEModelTag currentTag;

        public GEAnimationPlayer(GEModelTag tag)
        {
            if (tag == null)
                throw new ArgumentNullException("This tag does not contain any data!");

            currentTag = tag;
        }

        public void StartClip(GEAnimationClip clip)
        {
            if(clip == null)
                throw new ArgumentNullException("This animation does not contain any data!");

            currentTime = TimeSpan.Zero;
            currentKeyframe = 0;
        }

        public void Update(TimeSpan time, bool relativeToCurrentTime, Matrix rootTransform)
        {
            if (relativeToCurrentTime)
            {
                time += currentTime;

                while (time >= currentAnimation.Duration)
                    time -= currentAnimation.Duration;
            }

            if (time < TimeSpan.Zero || time > currentAnimation.Duration)
                throw new ArgumentOutOfRangeException("Time value is too large");

            if (time < currentTime)
                currentKeyframe = 0;

            currentTime = time;

            while (currentKeyframe < currentAnimation.KeyFrames.Count)
            {
                if (currentAnimation.KeyFrames[currentKeyframe].TimeSpan > currentTime)
                    break;

                keyframe = currentAnimation.KeyFrames[currentKeyframe].Transform;

                currentKeyframe++;
            }
        }

        public Matrix CurrentMatrix { get { return keyframe; } }

        public TimeSpan CurrentTime { get { return currentTime; } }

        public GEAnimationClip AnimationClip { get { return currentAnimation; } }
    }
}
